package ac.svn.accesscontrol.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import ac.svn.accesscontrol.store.ParsedItem;
import ac.svn.accesscontrol.store.SVNTag;

public class TagParser 
{
	public static final int TAG_GROUP 			=	1;
	public static final int TAG_LOCATION 	= 2;
	public static final int TAG_UNKNOWN  = -1;

	private int tagType = TAG_UNKNOWN;
	private String tagValue;
	private Map<String,Set<String>> parsedTag;

	public TagParser()
	{
		initParser();
	}

	private void initParser() {
		tagType = TAG_UNKNOWN;
		parsedTag = null;
		parsedTag = new HashMap<String, Set<String>>();
	}

	public void parseTag(SVNTag svnTag)
	{
		initParser();		
		getTagValue(svnTag.getTagText());
		ParsedItem parsedItem = null;
		for(String line: svnTag.getLines())
		{
			if(!line.trim().isEmpty())
			{
				parsedItem = new ParsedItem(line);
				if(parsedItem.isValid())
				{
					String lhsString = parsedItem.getLhsEntity();
					Set<String> rhs = parsedItem.getRhsEntities();
					parsedTag.put(lhsString, rhs);				
				}
			}
		}
	}

	private String getTagValue(String tagString)
	{
		tagValue = tagString.substring((tagString.indexOf('[') + 1),tagString.indexOf(']'));
		if(tagValue.toUpperCase(). contains("GROUPS"))
		{
			tagType = TAG_GROUP;
		}
		else if(tagValue.toUpperCase(). contains("/"))
		{
			tagType  = TAG_LOCATION;
		}
		else
		{
			tagType = TAG_UNKNOWN;
		}

		return tagValue.trim();
	}

	public int getTagType() {
		return tagType;
	}

	public void setTagType(int tagType) {
		this.tagType = tagType;
	}

	public String getTagValue() {
		return tagValue;
	}

	public void setTagValue(String tagValue) {
		this.tagValue = tagValue;
	}

	public Map<String, Set<String>> getParsedTag() {
		return parsedTag;
	}

	public void setParsedTag(Map<String, Set<String>> parsedTag) {
		this.parsedTag = parsedTag;
	}

}
